package com.lovo.Atm.service.impl;

import com.lovo.Atm.dao.UserDAO;
import com.lovo.Atm.dao.impl.UserDAOImpl;
import com.lovo.Atm.pojo.UserDO;
import com.lovo.Atm.service.UserService;


public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public UserDO getByNameAndPassword(String name, String password) {
        return userDAO.getByNameAndPassword(name, password);
    }

    @Override
    public void saveBlance(int id, double blance) {
        UserDO user = userDAO.geById(id);
        user.setBlance(user.getBlance() + blance);
        userDAO.update(user);
    }

    @Override
    public void remove(int id, double blance) throws Exception {
        UserDO user = userDAO.geById(id);
        //如果钱不够取，抛出异常给上一层处理，不能写JOptionPane.showMessageDialog();是因为现在是业务层
        if (user.getBlance() < blance){
            throw new Exception("余额不足");
        }
        user.setBlance(user.getBlance()-blance);
        userDAO.update(user);
    }

    @Override
    public void transfer(int mainId, String otherName, double balance) throws Exception {
        UserDO user = userDAO.geById(mainId);
        UserDO other = userDAO.getByUsername(otherName);
        if (otherName.equals(user.getName())) {
            throw new Exception("不能转账给自己");
        }
        if (other == null) {
            throw new Exception("查无此人");
        }
        if (balance > user.getBlance()) {
            throw new Exception("余额不足");
        }
        user.setBlance(user.getBlance() - balance);
        other.setBlance(other.getBlance() + balance);
        userDAO.update(user);
        userDAO.update(other);
    }

    @Override
    public void mod(int id, String oldPsw, String newPsw, String confirmPsw) throws Exception {
        UserDO user = userDAO.geById(id);
        if (user.getPassword().equals(oldPsw)) {
            if (confirmPsw.equals(newPsw)) {
                user.setPassword(newPsw);
                userDAO.update(user);
            } else {
                throw new Exception("确认密码错误");
            }
        } else {
            throw new Exception("旧密码错误");
        }
    }


}
